package com.yjd.merchant.api.login;

import com.yjd.comm.app.service.IMerchantPushRegidService;
import com.yjd.comm.base.control.MerchantBaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.device.service.IMerchantDeviceService;
import com.yjd.comm.enums.ApiRequestWayEnum;
import com.yjd.comm.merchant.model.MerchantModel;
import com.yjd.comm.merchant.service.IMerchantService;
import com.yjd.comm.org.service.IOrganizationService;
import com.yjd.comm.user.dto.MerchantSession;
import com.yjd.comm.util.*;
import com.yjd.comm.vo.CachedKeys;
import com.yjd.merchant.api.util.AccessTokenUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 商户登陆
 * Created by yangchangyan on 2017/8/16.
 */
@Controller("com.yjd.merchant.api.login.LoginControl")
@Scope("prototype")
@RequestMapping("/merchant")
public class LoginControl extends MerchantBaseControl {

    @Resource
    private IMerchantService merchantService;

    @Resource
    private IMerchantDeviceService merchantDeviceService;

    @Resource
    private IMerchantPushRegidService merchantPushRegidService;

    @Resource
    private IOrganizationService organizationService;

    /**
     * PC商户端登陆
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping(value = "/login")
    public void login(String username, String password) throws Exception {

        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            FrameUtil.throwBaseException1("参数不完整");
        }

        MerchantModel mModel = merchantService.login(username, password, ServletUtil.getIpAddr(request));

        if (null == mModel) {
            this.errorMsg("用户名或密码错误");
            return;
        }

        MerchantSession session = merchantService.getMerchantSession(mModel.getOrg_id());
        // 生成token
        String serverToken = AccessTokenUtil.generateAccessToken(session, ApiRequestWayEnum.WEB);

        Map<String, Object> userInfo = new HashMap<String, Object>();
        userInfo.put("org_id", mModel.getOrg_id());
        userInfo.put("username", mModel.getName());
        userInfo.put("last_login_time", mModel.getLast_login_time());
        userInfo.put("status", mModel.getStatus()); // 用户状态，0：可用，1：冻结

        this.successData(FrameUtil.newHashMap(
                "org_id", session.getOrg_id(),
                "access_token", serverToken,
                "userInfo",userInfo,
                "orgInfo", ResultMapBuilder.build(organizationService.getModelById(mModel.getOrg_id(), DbWREnums.READ))));
    }

    /**
     * PC商户端修改密码
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping(value = "/modify/password")
    public void modifyPassword(String oldPassword,String newPassword,String newPasswordConfirm) throws Exception {

        try{
            this.changePassword(oldPassword, newPassword, newPasswordConfirm);
        }catch (IllegalArgumentException iae){
            this.errorMsg(iae.getMessage());
            return;
        }

        this.request.setAttribute(CachedKeys.MERCHANT_USER, null);

        this.successMsg("修改成功");
    }

    /**
     * APP商户端登陆
     */
    @RequestMapping(value = "/app/login", method = RequestMethod.POST)
    public void appLogin(@RequestParam(required = false) String username,
                      @RequestParam(required = false) String password,
                      @RequestParam(required = false) String regid)
            throws Exception {

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);

        // 参数校验
        if (    StringUtil.isEmpty(username) ||
                StringUtil.isEmpty(password) ||
                StringUtil.isEmpty(regid) ||
                StringUtil.isEmpty(paramMap.get("device_name")) ||
                StringUtil.isEmpty(paramMap.get("device_no"))
                ) {
            this.errorMsg("参数不完整");
            return;
        }

        Map<String, String> param = FrameUtil.newHashMap(
                "device_name", paramMap.get("device_name").toString(),
                "device_no", paramMap.get("device_no").toString(),
                "regid", regid, "loginIp", ServletUtil.getIpAddr(request) );
        MerchantModel mModel = merchantService.mobileLogin(username, password, param);
        if (null == mModel) {
            this.errorMsg("用户名或密码错误");
            return;
        }

        MerchantSession session = merchantService.getMerchantMobileSession(mModel.getOrg_id());
        // 生成token
        String serverToken = AccessTokenUtil.generateAccessToken(session, ApiRequestWayEnum.APP);

        this.request.setAttribute(CachedKeys.MERCHANT_USER, session);

        Map<String, Object> merchantInfo = new HashMap<>();
        merchantInfo.put("username", username);
        merchantInfo.put("org_name", session.getOrg_name());
        merchantInfo.put("org_pic", ServletUtil.getFileUrl(session.getOrg_pic()));
        merchantInfo.put("last_login_time", DateUtil.timestampToDateString(session.getLast_login_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
        merchantInfo.put("status", session.getStatus()); // 状态，0：可用，1：冻结
        merchantInfo.put("org_address", CityUtil.getFullCityNames(session.getOrg_city(), "") + session.getOrg_address());

        this.successData(FrameUtil.newHashMap(
                "access_token", serverToken,
                "merchantInfo", merchantInfo,
                "org_id", mModel.getOrg_id()));
    }

    /**
     * APP商户端修改密码
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping(value = "/app/modify/password")
    public void appModifyPassword(String oldPassword,String newPassword,String newPasswordConfirm) throws Exception {

        try{
            this.changePassword(oldPassword, newPassword, newPasswordConfirm);
        }catch (IllegalArgumentException iae){
            this.errorMsg(iae.getMessage());
            return;
        }

        this.request.setAttribute(CachedKeys.MERCHANT_USER, null);

        this.successMsg("修改成功");
    }

    private void changePassword(String oldPassword,String newPassword,String newPasswordConfirm) throws Exception {
        if (StringUtil.isEmpty(oldPassword)||StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(newPasswordConfirm) ) {
            throw new IllegalArgumentException("参数不完整");
        }
        if(!newPassword.equals(newPasswordConfirm)){
            throw new IllegalArgumentException("两次新密码不一致");
        }
        MerchantSession session = super.getMerchantSession();
        String userPayPwd = SecurityCode.passwordMD5(oldPassword.trim(), session.getEncrypt());
        if (!session.getPassword().equals(userPayPwd)) {
            throw new IllegalArgumentException("原始密码错误");
        }
        MerchantModel mModel = new MerchantModel();
        mModel.setOrg_id(session.getOrg_id());
        mModel.setWhere_version(mModel.getVersion());
        // 验证通过，修改密码
        mModel.setPassword(SecurityCode.passwordMD5(newPassword, session.getEncrypt()));
        Long current = FrameUtil.getTime();
        mModel.setUpdate_time(current);
        mModel.setLast_login_time(current);
        merchantService.update(mModel);
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/app/logout", method = RequestMethod.POST)
    public void loginOut(@RequestParam(required = false) Long org_id, String device_no) throws Exception {

        if(StringUtil.isEmpty(org_id) || StringUtil.isEmpty(device_no)){
            this.errorMsg("参数错误");
            return;
        }

        merchantService.mobileLogout(org_id, device_no);

        this.request.setAttribute(CachedKeys.MERCHANT_USER, null);
        super.successMsg("退出登录成功");
    }

}
